package com.jzo2o.orders.manager.handler;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.base.model.domain.OrdersRefund;
import com.jzo2o.orders.manager.model.dto.OrderCancelDTO;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import com.jzo2o.orders.manager.service.IOrdersRefundService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class OrderHandler {

    @Resource
    private IOrdersManagerService ordersManagerService;
    @Resource
    private IOrdersRefundService ordersRefundService;

    /**
     * 支付超时取消订单
     * 每分钟执行一次
     */
    @XxlJob(value = "cancelOverTimePayOrder")
    public void cancelOverTimePayOrder() {
        //1. 查询超时(15分钟)未支付的订单
        List<Orders> list = ordersManagerService.queryOverTimeNoPayOrdersByCount(100);
        if (CollUtil.isEmpty(list)) {
            return;
        }
        //系统取消超时订单, 需要更改orders表的order_status, 新增orders_canceled表的记录
        for (Orders order : list) {
            OrderCancelDTO dto = BeanUtil.toBean(order, OrderCancelDTO.class);
            dto.setId(order.getId());
            dto.setCurrentUserType(UserType.SYSTEM);
            dto.setCancelReason("超时未支付自动取消订单");
            ordersManagerService.cancelNoPayOrder(dto);
        }
    }

    @XxlJob(value = "handleRefundOrders")
    public void handleRefundOrders() {
        //1.先查待退款记录
        List<OrdersRefund> ordersRefunds = ordersRefundService.queryRefundOrderListByCount(100);
        if (CollUtil.isEmpty(ordersRefunds)) {
            return;
        }
        //2.为这些待退款的订单处理退款操作
        for (OrdersRefund ordersRefund : ordersRefunds) {
            Orders orders = ordersManagerService.getById(ordersRefund.getId());
            ordersManagerService.requestRefundOrder(ordersRefund.getId(),ordersRefund.getRealPayAmount(),orders.getTradingOrderNo());
        }
    }
}
